<template>
  <div class="userContainer">
    <div class="search">
      <el-input v-model.trim="searchValue" placeholder="请输入用户名或用户电话" clearable :prefix-icon="Search" @keyup="getUserList(searchValue)">
        <template #append>
          <el-button :icon="Search" @click="getUserList(searchValue)"/>
        </template>
      </el-input>
      <!-- <el-button style="margin-left: 30px;" type="primary" @click="addUserVisible = true">新建用户</el-button>
      <el-button style="margin-left: 30px;" type="primary" @click="fileInPut = true">批量导入</el-button>
      <el-button type="success" @click="fileOutPut = true">导出</el-button> -->

      <el-dialog v-model="addUserVisible" title="添加用户" width="30%" draggable>
        <el-form v-model="addUserForm">
          <el-form-item prop="用户名称">
            <el-input v-model="addUserForm.userName" placeholder="请输入用户名" :prefix-icon="User"/>
          </el-form-item>
          <el-form-item prop="初始密码">
            <el-input v-model="addUserForm.password" placeholder="请输入用户初始密码" :prefix-icon="Lock"/>
          </el-form-item>
          <el-form-item prop="联系电话">
            <el-input v-model="addUserForm.tel" placeholder="请输入用户电话" :prefix-icon="Iphone"/>
          </el-form-item>
          <el-form-item prop="学院信息">
            <el-cascader v-model="addUserForm.collegeMessage" :options="collegeOptions" @change="handleChange" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addUserVisible = false">取消</el-button>
            <el-button type="primary" @click="addUser()">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 导出表格弹框 -->
     <el-dialog v-model="fileOutPut" title="表格导出" width="30%" @close="close">
            <el-input v-model="name" placeholder="请输入导出文件的文件名"></el-input>
            <el-alert title="默认文件名为（导出测试）" type="info" :closable="false" style="margin-top: 10px;" />
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="fileOutPut = false">取消</el-button>
                    <el-button type="primary" @click="save">确定</el-button>
                </span>
            </template>
      </el-dialog>
    <el-table :data="tableData" stripe style="width: 100%;margin-top: 10px;" height="50%" id="el-table">
    <el-table-column prop="userId" label="用户ID" width="200"/>
    <el-table-column prop="nickName" label="微信昵称" width="200"/>
    <el-table-column prop="avatarUrl" label="微信头像" width="200">
         <template #default="{ row }">
           <img :src="row.avatarUrl" alt="微信头像" style="width: 50px; height: 50px; border-radius: 50%;" />
         </template>
       </el-table-column>
    <el-table-column prop="wechatOpenid" label="微信openId" width="200"/>
    <el-table-column prop="phone" label="电话" />
    <el-table-column prop="points" label="目前积分" />
    <el-table-column prop="univerName" label="所在学校" />
    <el-table-column prop="collegeName" label="所在校区" width="150" />
    <el-table-column fixed="right" label="操作" width="125">
      <template #default="row">
        <el-tooltip content="授予积分" placement="bottom">
          <el-button link type="primary" :icon="Edit" class="myLink" @click="getDetailMessage(row)" style="font-size: 15px;">授予积分</el-button>
        </el-tooltip>
        <el-tooltip content="积分详情" placement="bottom">
          <el-button link type="primary" :icon="Edit" class="myLink" @click="getDetailPoints(row)"  style="font-size: 15px;">积分详情</el-button>
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="detailMessage" title="发放积分" width="30%" draggable>
    <el-form v-model="detailUser" label-position="left">
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model="detailUser.userId" autocomplete="off" disabled/>
      </el-form-item>
      <el-form-item label="积分" prop="points">
        <el-input v-model="detailUser.points" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="detailUser.description" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailMessage = false">取消</el-button>
        <el-button type="primary" @click="collegeEdit()">确定发放</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogVisible" title="积分详情" width="60%" draggable>
         <el-table :data="pointsDetailData" stripe style="width: 80%">
           <el-table-column prop="createTime" label="日期" width="350"  :formatter="formatDate"/>
           <el-table-column prop="pointsAmount" label="积分数量" width="150" />
           <el-table-column prop="recordsType" label="类型" width="150" :formatter="formatRecordsType" />
           <el-table-column prop="description" label="原因" />
         </el-table>
  </el-dialog>
  <div class="pagination">
    <el-pagination v-model:current-page="page" v-model:page-size="size" :page-sizes="[5,10,20,30]" :small="small" :disabled="disabled"
      :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>
  </div>
</template>

<script setup>
import { reactive , inject , onMounted , ref ,nextTick} from "vue"
import axios from '../../axios/axiosInstance'
import { ElLoading ,ElMessage,ElMessageBox} from 'element-plus'
import { Delete ,Search ,User,Lock,Iphone,Postcard,UploadFilled} from '@element-plus/icons-vue'
import FileSaver from "file-saver";
import * as XLSX from 'xlsx';
// import FileIn from "../../components/file/Excel.vue"

//变量定义
const addUserVisible = ref(false)
let name = "";
const fileOutPut = ref(false)
const fileInPut = ref(false)
const collegeOptions = reactive()
let tableData = reactive([])
let pointsDetailData = reactive([])
let dialogVisible = ref(false)
let addUserForm = reactive({
  userName: "",
  tel: "",
  password: "",
  collegeMessage: "",
})
let detailMessage = ref(false)
const total = ref(0)
let searchValue = ref()
let page = 1
let size = 5
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const detailUser = reactive({
  userId: "",
  points: 0,
  description: "",
})

//方法 

const getDetailMessage = (row) => {
  detailMessage.value = true;
  detailUser.userId = row.row.userId;
}

const formatDate = (row, column, cellValue)=> {
       if (cellValue) {
         const date = new Date(cellValue);
         return date.toLocaleString(); // 根据需求调整格式
       }
       return '';
     }

const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  size = val
  init()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  page = val
  init()
}

const formatRecordsType = (row, column, cellValue) => {
       return cellValue === 0 ? '获取' : '消费';
     }

const filterName = (value, row) => {
  return row.roleName === value
}


 const clear = (value) => {
    Object.keys(value).map(key => {
      delete value[key]
    })
  }

  const handleChange = (value) => {
    console.log()
  console.log(value)
}

const collegeEdit = () => {
   axios.post('/user/pointsGive',detailUser).then((res) => {
    console.log(res)
    if(res.code == 200){
      ElMessage({type: "success",message: "发放成功"});
      detailMessage.value = false;
      clear()
      init();
    }else{
      ElMessage({type: "error",message: "编辑失败"});
    }
  }).catch((err) => {
    console.log(err)
  })
}

const getDetailPoints = (row) => {
  dialogVisible.value = true;
  axios.get('/points-records/list/'+row.row.userId,detailUser).then((res) => {
    console.log(res)
    if(res.code == 200){
      ElMessage({type: "success",message: "获取成功"});
      clear(pointsDetailData);
      for(let i in res.data){
        console.log(i)
        pointsDetailData.push(res.data[i])
      }
      dialogVisible.value = true;
    }else{
      ElMessage({type: "error",message: "编辑失败"});
    }
  }).catch((err) => {
    console.log(err)
  })
}

// const save = () => {
//    nextTick(function () {
//         let filename = ''
//         const xlsxParam = { raw: true } //转化成Excel使用原始格式
//         const elTable = XLSX.utils.table_to_book(document.getElementById('el-table'), xlsxParam)
//         if (name === '') {
//         	// 默认导出文件名
//             filename = '导出测试.xlsx'
//         } else {
//             filename = name += '.xlsx'
//         }
//         const wbout = XLSX.write(elTable, { bookType: 'xlsx', bookSST: true, type: 'array' })
//         try {
//             FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename)
//         } catch (e) {
//             if (typeof console !== 'undefined') {
//                 console.log(e, wbout)
//             }
//         }
//         return wbout
//     })
// }

// const addUser = () => {
//    //将数据发往后端
//    console.log(addUserForm)
//   axios.post('/account-service/user/oneUser/',addUserForm).then((res) => {   
//         console.log("res是：")
//         console.log(res)
//         console.log("res.data是：")
//         console.log(res.data)
//         console.log("res.data.data是：")
//         console.log(res.data)
//         if(res.code == 200){
//           //添加管理员成功成功
//           ElMessage({type: "success",message: "添加成功"});
//           tableData.push(res.data)
//         }else{
//           //登录失败
//          ElMessage({type: "error",message: res.msg})
//          addAdminVisable = false;
//         }
//     }).catch((err) => {
//       console.log(err)

//     })
// }


// const getInitOptions = () => {
//    axios.get('/contact-service/college/collegeOption').then((res) => {   
//         console.log("res是：")
//         console.log(res)
//         console.log("res.data是：")
//         console.log(res.data)
//         console.log("optionsoptions是：")
//         console.log(res.data)
//         if(res.code == 200){
//           collegeOptions = res.data
//           console.log("得到的值为：")
//           console.log(collegeOptions)
//         }else{
//         }
//     }).catch((err) => {
//       console.log(err)

//     })
// }
// const deleteUser = (row) => {
//   console.log(row);
//   console.log(row.row);
//   console.log(row.$index)
//   console.log(row.row.userId);
//   let name = row.row.userName
//   ElMessageBox.confirm(
//     '确定要删除用【'+name+'】吗？',
//     '温馨提示',
//     {
//       confirmButtonText: 'OK',
//       cancelButtonText: 'Cancel',
//       type: 'warning',
//     }
//   )
//     .then(() => {
//       let userId = row.row.userId;
//       console.log(userId)
//       axios.delete('/account-service/user/deleteOne/'+userId).then((res) => {
//         console.log(res)
//         if(res.code == 200){
//           ElMessage({type: "success",message: "删除成功"});
//           tableData.pop(row.$index)
//         }else{
//           ElMessage({type: "error",message: "删除失败"});
//        }
//       }).catch((err) => {
//         console.log(err)
//       })
//     })
//     .catch(() => {
//       ElMessage({
//         type: 'info',
//         message: '删除取消',
//       })
//     }) 

// }

//根据关键字模糊查询用户
const getUserList = (searchValue) => {
  if(searchValue != ''){
    axios.post(`/user/list`,{
      page: page,
      size: size,
      admin: false,
      username: searchValue,
    }).then((res) => {
        console.log(res)
        if(res.code == 200){
          clear(tableData)
          total.value = res.data.total;
          for(let i in res.data.records){
            console.log(i)
            tableData.push(res.data.records[i])
          }
          ElMessage({type: "success",message: "查询成功"});
        }else{
          ElMessage({type: "error",message: "查询失败"});
       }
      }).catch((err) => {
        console.log(err)
      })
  }else{
    init()
  }
}

const init = () => {
  const loading = ElLoading.service({
        lock: true,
        text: '拼命加载中',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      setTimeout(() => {
        loading.close()
      }, 2000)
     axios.post(`/user/list`,{
      page: page,
      size: size,
      admin: false,
     }).then((res) => {   
      console.log(res)
      clear(tableData)
      total.value = res.data.total
      console.log(total)
      for(let i in res.data.records){
        console.log(i)
        tableData.push(res.data.records[i])
      }
      console.log("最后的tableData是：")
      console.log(tableData)
    }).catch((err) => {

      console.log(err)

    })
}

//页面初始化方法
onMounted(()=>{ 
  init()
  // getInitOptions()
})
</script>

<style scoped>
.userContainer .search{
  display: flex;
  width: 600px;
}
.userContainer .pagination{
  justify-content: center;
 margin-top: 15px;
}

</style>
